//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.candy.common.utils;

import com.candy.common.annotations.Lock;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.StandardReflectionParameterNameDiscoverer;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import java.lang.reflect.Method;

/**
 * 获取Spel表达式值
 *
 * @author rong xi
 * @version 1.0
 * @date 2023/09/14 18:28
 */
public class SpelUtil{
    private static final SpelExpressionParser PARSER = new SpelExpressionParser();
    private static final StandardReflectionParameterNameDiscoverer DISCOVERER = new StandardReflectionParameterNameDiscoverer();


	public static String getKeyValue(Lock lock, JoinPoint point) {
        Object[] arguments = point.getArgs();
        String[] params = DISCOVERER.getParameterNames(getMethod(point));
        StandardEvaluationContext context = new StandardEvaluationContext();
        if (params != null && params.length > 0) {
            for(int len = 0; len < params.length; ++len) {
                context.setVariable(params[len], arguments[len]);
            }
        }

        Expression expression = PARSER.parseExpression(lock.key());
        return expression.getValue(context, String.class);
    }

    private static Method getMethod(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        if (method.getDeclaringClass().isInterface()) {
            try {
                method = joinPoint.getTarget().getClass().getDeclaredMethod(joinPoint.getSignature().getName(), method.getParameterTypes());
            } catch (NoSuchMethodException | SecurityException var5) {
                throw new RuntimeException(var5);
            }
        }

        return method;
    }
}
